package com.ryan.util;

import java.io.IOException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class HttpUtil {
	private static final String TAG = "HttpUtil";
	private static String uri = "http://sbapi.sinaapp.com/";
	private static String encoding = "utf-8";

	public static class HttpResult {
		private int code;
		private JSONObject json;
		private String error;

		public int getCode() {
			return code;
		}

		public JSONObject getJson() {
			return json;
		}

		public String getError() {
			return error;
		}
	}

	public static HttpResult executeGet(String req,List<NameValuePair> parameters){
		HttpResult result = new HttpResult();

		String url = uri+req+"?"+encode(parameters);
        HttpClient client = genHttpClient();
		HttpGet get = new HttpGet(url);
		try {
			HttpResponse response = client.execute(get);
			int code = response.getStatusLine().getStatusCode();
			String resEntity = EntityUtils.toString(response.getEntity());
			if(code == HttpStatus.SC_OK){
				result.code = HttpStatus.SC_OK;
				result.json = new JSONObject(resEntity);
			}else{
				result.code = code;
				result.error = resEntity;
			}
		} catch (ClientProtocolException e) {
			LogUtil.e(TAG, "e",e);
			result.code = Constant.CODE_HTTP_ClientProtocolException;
			result.error = e.getMessage();
		} catch (IOException e) {
			LogUtil.e(TAG, "e",e);
			result.code = Constant.CODE_HTTP_IOException;
			result.error = e.getMessage();
		} catch (Exception e) {
			LogUtil.e(TAG, "e",e);
			result.code = Constant.CODE_HTTP_Exception;
			result.error = e.getMessage();
		}
		
		LogUtil.v(TAG, "execute["+url+"]"+"result["+result.code+","+result.json+","+result.error);
		
		return result;
	}
	
	public static boolean isSuccess(HttpResult res){
		return res.getCode() == HttpStatus.SC_OK;
	}
	
	private static HttpClient genHttpClient(){
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
        HttpConnectionParams.setSoTimeout(httpParams, 30000);
        return new DefaultHttpClient(httpParams);
	}
	
	private static String encode(List<NameValuePair> parameters){
		if(parameters == null ||  parameters.size()==0)
			return "";
		return URLEncodedUtils.format(parameters, encoding);
	}
}
